<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://yoursite.com/page/4/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<meta name="twitter:description">
  
    <link rel="alternative" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  

</head>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main">
  
    <article id="post-gis/4.常用资料" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/17/gis/4.常用资料/" class="article-date">
  <time datetime="2016-01-17T12:00:00.000Z" itemprop="datePublished">2016-01-17</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/gis/">gis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/17/gis/4.常用资料/">常用资料</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u5217_u8868"><a href="#u5217_u8868" class="headerlink" title="列表"></a>列表</h2><p>　　轻量级的web map框架：leaflet<br>　　地图相关博客：<a href="http://www.cnblogs.com/shitao/category/331988.html" target="_blank" rel="external">http://www.cnblogs.com/shitao/category/331988.html</a><br>　　坐标系换算：<a href="http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames" target="_blank" rel="external">http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames</a><br>　　openlayers加载球面墨卡托数据：<a href="http://docs.openlayers.org/library/spherical_mercator.html" target="_blank" rel="external">http://docs.openlayers.org/library/spherical_mercator.html</a></p>
<p>　　ol矢量图层面填充支持graphicfill填充：<a href="http://www.cnblogs.com/shitao/archive/2012/08/14/2636874.html" target="_blank" rel="external">http://www.cnblogs.com/shitao/archive/2012/08/14/2636874.html</a><br>　　<a href="http://dev.openlayers.org/sandbox/ossipoff/openlayers/examples/graphicfill.html" target="_blank" rel="external">http://dev.openlayers.org/sandbox/ossipoff/openlayers/examples/graphicfill.html</a></p>
<p>　　矢量栅格化工具：TileCache、TileStache</p>
<h2 id="u6BD4_u4F8B_u5C3A_u4E0E_u5206_u8FA8_u7387"><a href="#u6BD4_u4F8B_u5C3A_u4E0E_u5206_u8FA8_u7387" class="headerlink" title="比例尺与分辨率"></a>比例尺与分辨率</h2><p>1米 = 39.37007英寸<br>1英寸 包含72个像素点<br>分辨率resolutions：每个像素点代表的实际地理距离</p>
<p>openlayers计算出来的<br>第0级比例尺 443743145.6320125<br>第0级分辨率：156543.03390625（一张256像素的瓦片），156543.03390625 * 256 = 40075016.68米，恰好为赤道周长</p>
<p>第0级 比例尺：156543.03390625 <em> 72 </em> 39.37007 = 443743934.6089034 意即图上一米代表的实际距离多少米<br>第1级 比例尺：443743934.6089034 / 2 = 221871967.3044517<br>第2级 比例尺：221871967.3044517 / 2 = 110935983.6522259</p>
<p>　　在GIS中所提到的 分辨率，也称地面分辨率（Ground Resolution）或空间分辨率（Spatial Resolution），表示一个像素（pixel）代表的地面实际距离。 以谷歌地图为例：在缩放级别为 1 时，图片大小为4个 256<em>256 的图片，那么赤道上的空间分辨率为：地球赤道周长（实地距离）除以256</em>2（像素大小）。其他纬度上的分辨率则为：纬度圈长度/512。 因此可以看出，分辨率取决于两个参数，纬度和缩放级别，缩放级别决定了像素的多少，纬度决定了地面距离的长短。 因此谷歌地图某视图下的分辨率计算公式为（单位：米/像素）：<img src="/images/utionFormula.png" alt="utionFormula.png"><br>F(X,Y):地图分辨率；<br>X：纬度值；<br>Y：缩放级别；<br>R：常量 6378137，表示地球半径，单位：米。<br>　　比例尺，通常以比率(如 1:10000 )来表示，表示图上距离与实地距离之比。例如 1:10000 表示图上 1cm 代表实际距离 10000cm，即100米。 由于比例尺起源较早，通常用（纸质）图上的距离衡量实际距离；而分辨率则通常用设备屏幕上的距离来衡量实际距离。而同一个地图视图，尺度是唯一的，比例尺和分辨率只不过是两种表示方法，因此它们是一一对应的。 比例尺与分辨率之间的换算公式如下：<img src="/images/ScaleFormula.png" alt="ScaleFormula.png"><br>Scale：地图比例尺；<br>Resolution：地图分辨率；<br>PPI：每英寸的像素点数。<br>　　其中 PPI，即 Pixel per Inch，即每英寸的像素点数（在不混淆情况下，也有用 DPI 来表示该参数）。0.0254 为英寸和米的转换常数。<br>　　由于比例尺和分辨率一一对应，因此比例尺也取决于纬度和缩放级别两个参数，并且还与 PPI 相关。仍旧以谷歌地图为例：当地图处于全幅状态时，上下移动地图，使得地图中心线处纬度发生变化，因此比例尺随之变化；同理，当地图处于不同的缩放级别时，地图比例尺同样也会发生变化。如图1 和图2，纬度和缩放级别的变化引起了比例尺的变化。注意：视图下的比例尺一般指中心点的比例尺。（上下平移地图，可以看出地图的比例尺发生了变化）<br>　　但图3和图4相比，上下移动地图时，地图比例尺并未发生变化。这是由于缩放级别较大时，即地图处在较大比例尺状态，地图上下平移，所造成的纬度变化非常小，因此比例尺就基本相等。<br><img src="/images/MoveMap1.png" alt="MoveMap1.png"><img src="/images/MoveMap2.png" alt="MoveMap2.png"><img src="/images/MoveMap3.png" alt="MoveMap3.png"><img src="/images/MoveMap4.png" alt="MoveMap4.png"><br>　　那么，在 SueperMap iClient 产品中 Map 和 Layer 对象同时拥有比例尺和分辨率属性，该如何进行选择呢？<br>　　如果 SueperMap iClient 产品的后台服务器产品选择 SuperMap 系列服务器产品，建议使用 Map 与 Layer 中的比例尺相关属性（比如 Scale、Scales 等），因为 SuperMap 服务器直接提供了相关地图的比例尺功能。 如果后台服务器产品并没有直接提供比例尺，或者是在 WMS 这类标准服务中未涉及比例尺参数的情况下，建议选择分辨率属性（比如 Resolution、Resolutions 等）。 这是因为比例尺与用户屏幕相关的，而分辨率则是无关的。图5和图1展示的地图是同一级别，却显示了不同的比例尺。原因就在于两幅图来源的用户电脑屏幕分辨率不同。而屏幕分辨率的不同导致了了 PPI 的变化，从计算比例尺的公式可以看出，比例尺必然发生变化。<br><img src="/images/ScaleMap.png" alt="不同屏幕分辨率下的截图"><br>　　而分辨率却没有变化，因为该级别下，赤道周长仍旧没变，图片也仍旧是 512*512 像素，因此可知分辨率与屏幕分辨率没有关系。<br>另外，在 WMS 参数中有 bbox、height 和 width 这三个参数可唯一确定所请求的地理视图范围与缩放级别。bbox 指可视的地理范围，由4个边界值可确定中心点，而 bbox 的宽度（实地距离）除以 width（图片距离）即是 Resolution（分辨率）。但是没有 PPI，是不能确定 Scale （比例尺）的。换句话说，由 Resolution、Center、Width、Height 可唯一确定某个可视范围，但仅有 Sclae、Center、Width、Height 却无法确定。而在利用 SuperMap 服务器提供的服务时，由 Sclae、Center 参数（宽和高一般都有默认值）可确定唯一的可视范围。这其中的原因是，SuperMap 服务器默认使用了出图服务器的PPI。有经验的用户会发现，在改变了出图服务器的分辨率时，用同样的 Sclae、Center 请求的图片却是不一样的。<br>参考网站：<a href="http://support.supermap.com.cn/DataWarehouse/WebDocHelp/6.1.1/iServerJavaOnlineHelp/mergedProjects/sl/G_MapAndLayer/L_ResolutionAndScale.html" target="_blank" rel="external">http://support.supermap.com.cn/DataWarehouse/WebDocHelp/6.1.1/iServerJavaOnlineHelp/mergedProjects/sl/G_MapAndLayer/L_ResolutionAndScale.html</a></p>
<h2 id="ol_u7F29_u653E_u7EA7_u522B_u8BBE_u7F6E"><a href="#ol_u7F29_u653E_u7EA7_u522B_u8BBE_u7F6E" class="headerlink" title="ol缩放级别设置"></a>ol缩放级别设置</h2><p>　　在OpenLayers中，地图必须具有一个缩放级别的范围，缩放级别可以用比例尺（scale）或者分辨率（resolution）表示。比例尺——屏幕上1米代表多少地图坐标单位；分辨率——屏幕上一个像素代表多少地图坐标单位。两者的转换关系是：scale = resolution <em> 72 </em> 39.3701（1米=39.3701英寸，1英寸=72像素）。地图具有一个总的缩放级别，每个图层可以有各自的缩放级别，这样可以控制图层只在合适的级别上显示。<br>　　缩放级别范围的确定方法<br>　　1. 比例尺数组或者分辨率数组来确定（相邻两级之间不一定是2倍的关系，可以是任意值）。示例：<br>resolutions: [1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125]<br>scales: [50000000, 30000000, 10000000, 5000000]<br>　　2. 用最大分辨率（maxResolution）和缩放级别总数（numZoomLevels）确定，相邻两级是2倍关系</p>
<p>　　最大分辨率的确定方法：<br>    a. 直接指定maxResolution，例如：maxResolution: 0.17578125<br>    b. 直接指定minScale，例如：minScale: 50000000<br>    c. 由maxExtent确定（maxResolution需设置为‘auto’），例如：{maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90), maxResolution: “auto”}<br>　　缩放级别总数的确定方法：<br>　　1. 直接指定numZoomLevels，例如：numZoomLevels: 5<br>　　2. 由最大分辨率和最小分辨率的比值确定，最小分辨率同2.1有三种方法可以确定：<br>        2.1 直接指定minResolution<br>        2.2 直接指定maxScale<br>        2.3 由minExtent确定（minResolution需设置为‘auto’）</p>
<p>如果指定的参数过多，导致缩放级别范围不一致时，上述方法顺序决定了OpenLayers确定缩放级别范围的优先级。</p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://schemas.opengis.net/" target="_blank" rel="external">http://schemas.opengis.net/</a><br><a href="http://www.cnblogs.com/sailheart" target="_blank" rel="external">http://www.cnblogs.com/sailheart</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/17/gis/4.常用资料/" data-id="cijzzpvfm00f21cfsu1ujgva2" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/gis/">gis</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/10.序列化框架深入分析" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/17/java/10.序列化框架深入分析/" class="article-date">
  <time datetime="2016-01-17T06:08:00.000Z" itemprop="datePublished">2016-01-17</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/17/java/10.序列化框架深入分析/">序列化框架深入分析</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u5E8F_u5217_u5316"><a href="#u5E8F_u5217_u5316" class="headerlink" title="序列化"></a>序列化</h2><p>　　把对象转换为字节序列的过程称为对象的序列化，把字节序列恢复为对象的过程称为对象的反序列化。对象的序列化主要有两种用途：1. 把对象的字节序列永久地保存到硬盘上，通常存放在一个文件中；2. 在网络上传送对象的字节序列。<br>　　在java的生态体系统中，我们可以找到很多不同的序列化产品，他们各有优缺点，下面我就从序列化速度和序列化后字节大小两个方面分析一下知名的序列化框架，比如：protobuf、thrift、avro、kyro、messagePack和jdk的Serializable接口，在最后，我们会实现一个简单的二进制编解码功能，完整的测试代码详见文章最后附件。<br>　　本文不会涉及到各序列化框架的基础部分，如果需要请自行查找资料！这里先贴出测试结果：可以看到protobuf无论是在速度还是序列化大小方面几乎都是最好的，非常适合于即使通信领域的数据协议交换格式！</p>
<table>
<thead>
<tr>
<th style="text-align:center">框架</th>
<th style="text-align:center">协议</th>
<th style="text-align:center">大小(字节)</th>
<th style="text-align:center">序列化<br>500w次(毫秒)</th>
<th>反序列化<br>500w次(毫秒)</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">jdk</td>
<td style="text-align:center">—</td>
<td style="text-align:center">115</td>
<td style="text-align:center">8234毫秒</td>
</tr>
<tr>
<td style="text-align:center">protobuf</td>
<td style="text-align:center">—</td>
<td style="text-align:center">16</td>
<td style="text-align:center">243毫秒</td>
</tr>
<tr>
<td style="text-align:center">thrift</td>
<td style="text-align:center">TBinaryProtocol</td>
<td style="text-align:center">27</td>
<td style="text-align:center">1544毫秒</td>
</tr>
<tr>
<td style="text-align:center">thrift</td>
<td style="text-align:center">TCompactProtocol</td>
<td style="text-align:center">17</td>
<td style="text-align:center">1345毫秒</td>
</tr>
<tr>
<td style="text-align:center">thrift</td>
<td style="text-align:center">TTupleProtocol</td>
<td style="text-align:center">15</td>
<td style="text-align:center">1102毫秒</td>
</tr>
<tr>
<td style="text-align:center">messagePack</td>
<td style="text-align:center">—</td>
<td style="text-align:center">15</td>
<td style="text-align:center">5846毫秒</td>
</tr>
<tr>
<td style="text-align:center">avro</td>
<td style="text-align:center">SpecificDatumWriter</td>
<td style="text-align:center">17</td>
<td style="text-align:center">6215毫秒</td>
</tr>
<tr>
<td style="text-align:center">avro</td>
<td style="text-align:center">ReflectDatumWriter</td>
<td style="text-align:center">17</td>
<td style="text-align:center">6660毫秒</td>
</tr>
<tr>
<td style="text-align:center">kyro</td>
<td style="text-align:center">writeClassAndObject</td>
<td style="text-align:center">16</td>
<td style="text-align:center">4748毫秒</td>
</tr>
<tr>
<td style="text-align:center">kyro</td>
<td style="text-align:center">writeObject</td>
<td style="text-align:center">15</td>
<td style="text-align:center">4929毫秒</td>
</tr>
<tr>
<td style="text-align:center">kyro</td>
<td style="text-align:center">writeClassAndObject</td>
<td style="text-align:center">16</td>
<td style="text-align:center">4832毫秒</td>
</tr>
<tr>
<td style="text-align:center">kyro</td>
<td style="text-align:center">writeObject</td>
<td style="text-align:center">15</td>
<td style="text-align:center">4897毫秒</td>
</tr>
</tbody>
</table>
<h2 id="jdk_u5E8F_u5217_u5316"><a href="#jdk_u5E8F_u5217_u5316" class="headerlink" title="jdk序列化"></a>jdk序列化</h2><p>　　Java的序列化算法一般会按步骤做如下事情：<br>　　1. 将对象实例相关的类元数据输出，包括：类名、字段类型（比如java.lang.Strng）、名称和serialVersionID等信息。<br>　　2. 递归地输出类的超类描述直到不再有超类。<br>　　3. 类元数据完了以后，开始从最顶层的超类开始输出对象实例的实际数据值。<br>　　4. 从上至下递归输出实例的数据<br>　　从上面的步骤可以看出，采用jdk序列化得到的二进制数据含有大量的元数据信息，这样可以很好的保证其兼容性的问题。但是在特定的应用场景下，特别是移动网路中，考虑到网络稳定性和流量消耗的问题，我们更关注的是数据传输时的大小和编解码的效率，而协议的兼容性问题可以通过其他的方式解决！在介绍protobuf、thrift等实现原理之前，我们先看看tlv（tag length value）思想！</p>
<h2 id="TLV"><a href="#TLV" class="headerlink" title="TLV"></a>TLV</h2><p>　　TLV即Tag-Length-Value，可以看到，TLV的定义包括三个域，分别为：标签域（Tag）、长度域（Length）和内容域（Value）。这里的长度域的值实际上就是内容域的长度。同时，其编码方式有两种情况，一种是确定长度的方式，一种是不确定长度的方式，而金融TLV选择了确定长度的方式。这里我们先解释一下这几个域的数据结构：<br>　　<strong>Tag域</strong>：TLV的Tag是如何编码的，先看下图：<img src="/images/tlv-tag.png" alt="tlv-tag.png"><br>　　说明了Tag域第一个字节的编码格式。其中b8-b1代表1个字节中的8个位。其中b8，b7代表数据的类别。根据2个位的组合，有四种类别：通用类别、应用类别、上下文语境类别和专用类别。这个主要用于在于终端设备交互的时候，确定数据处理的类型。<strong>b6代表的是数据元结构，也就是说它是属于简单数据元结构，还是属于结构（复合）数据元结构</strong>。当b6为1的时候，就需要后续的字节进行扩展。也就是说复合的TLV中，value域里也包含一个或多个TLV，这个稍后接着介绍。<br>　　当b5-b1代表串行号，当5个位都为1时，需要将tag域扩展到下一个字节中，也就是Tag占2个字节；而当5个位都不全为1时，该Tag域就只占1个字节。现在，看下b5-b1：11111的情况：<img src="/images/tlv-tag2.png" alt="tlv-tag2.png"><br>　　从图中我们看到BER-TLV编码中，当b8为1时，Tag还需要有后续字节，直到b8为0为止。从EMV文档中的说明，Tag最多只占用2个字节，所以这样就相对比较简单一些了。当b8为0时，该Tag域结束，总共就占用2个字节。<br>　　<strong>Length域</strong>：默认一个字节长度，当b8（最高位）为0时，该字节的b7-b1作为value域的长度；当b8为1时，b7-b1作为后续字节的长度，也就是说，例如有这样一个值：10000011，代表后续还有3个字节作为value域的长度（本字节不算，本字节变为作为一个Length的索引）。<br>　　<strong>Value域</strong>：这里需要分成两种情况考虑，如果value是一个简单的数据，比如int、string等，则就是实际的值。但如果value值是一个复杂的数据结构，则存储的则为TLV格式的。<br>　　下面介绍的Protobuf序列化机制就是在该机制的原理上进行了调整，实现了更高效的序列化！</p>
<h2 id="Protobuf"><a href="#Protobuf" class="headerlink" title="Protobuf"></a>Protobuf</h2><p>　　Protobuf是鼎鼎大名的Google公司开发出来，并在Google内部久经考验的一个产品。它通过自定义二进制协议的方式，实现了极致的序列化过程</p>
<h4 id="Variants"><a href="#Variants" class="headerlink" title="Variants"></a>Variants</h4><p>　　Protobuf对数据编码时，采用了一种叫做Variants的技术。顾名思义，Varints是一种紧凑表示数字的方法。它用一个或者多个字节表示一个数字，值越小的数字字节数越少。相对于传统的用4字节表示int32类型数字，Varints对于小于128的数值都可以用一个字节表示，大于128的数值会用更多的字节来表示，比如150，就会用两个字节表示。Varints算法总体来说就是，<strong>Varints中每一个字节的最高位(官方叫most significant bit，简称MSB)如果是1，则表示后续的字节也是该数字的一部分；如果是0，则结束</strong>。所以当数字为&lt;128时，比如10，则会用一个字节来表示：00001010。如果数字是150的话，则会用两个字节来表示：10010110 00000001。其详细的计算过程为：<br>　　上述最高位是MSB，表明后续的字节也属于本数值。第二个字节MSB为0，表明结束。所以去掉MSB以后为:0010110 0000001。<strong>Protobuf是小字节序</strong>，所以再反序一下变成：0000001 0010110 =&gt; 10010110，转换成10进制就是150。我们先看看下面的测试用例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">protobufTest</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    ProtobufMsg.Msg.Builder builder = ProtobufMsg.Msg.newBuilder();</span><br><span class="line">    builder.setType(type);</span><br><span class="line">    builder.setBody(msg);</span><br><span class="line">    ProtobufMsg.Msg deviceMsg = builder.build();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">byte</span>[] bytes = deviceMsg.toByteArray();</span><br><span class="line"></span><br><span class="line">    System.out.println(<span class="string">"protobuf序列化后大小:"</span> + bytes.length);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">long</span> startTime = System.nanoTime();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; cycleIndex; i++) &#123;</span><br><span class="line">        deviceMsg.toByteArray();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">long</span> endTome = System.nanoTime();</span><br><span class="line">    System.out.println(String.format(<span class="string">"protobuf序列化%d次共耗时%d毫秒"</span>, cycleIndex, (endTome - startTime) / <span class="number">1000</span> / <span class="number">1000</span>));</span><br><span class="line">    System.out.println();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　这里，Msg有三个字段，但是只对type(int)和body(String)两个属性设置了值。<br>　　<strong>type属性序列化的过程</strong>：<br>　　1. 首先type字段的编号在protobuf描述文件中已经定义了，取值为1。在生成的java类中则用field_number=1表示<br>　　2. 计算其Tag值，算法为：(field_number &lt;&lt; 3) | wire_type，此处wire_type的类型则为WireFormat.WIRETYPE_VARINT=0，计算出的tag结果为(1 &lt;&lt; 3) | 0 = 8<br>　　3. 由于type为基本类型，所以type序列化后的字节为8和1（无需length域指定数字占用的字节长度），共占用2个字节<br>　　<strong>body属性的序列化过程</strong>：<br>　　1. 首先body字段的编号在protobuf描述文件中已经定义了，取值为3。在生成的java类中则用field_number=3表示<br>　　2. 计算其Tag值，算法不变，只是此时wire_type取值为：WireFormat.WIRETYPE_LENGTH_DELIMITED=2，计算出的tag结果为 (3 &lt;&lt; 3) | 2 = 26<br>　　3. 由于body为字符串类型，需要length域指定值的字节长度，序列化的二进制内容为：26、12(“测试内容”的utf8编码后长度)以及测试内容，共占用14个字节<br>　　type和body序列化后的大小总共为16个byte，与日志输出一致。我们可以这样理解Tag：其低三位表示value的类型，剩下的高位表示field的真正index。<br>　　通过对序列化过程的分析，我们可以发现：<strong>protobuf序列化后的二进制数据是没有记录数据类型的</strong>，所以如果只给出protobuf序列化后的二进制数据，是无法知道其数据类型的。在大多数的应用系统中，有多种不同结构的数据，采用protobuf框架的话，就需要通过其他的手段区别不同的二进制数据类型！</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　理解了protobuf的原理之后，其他的框架，比如thrift等的原理基本上也就明白了，这里不再做过多的介绍。核心思想基本上都是：给每一个属性编号，用数字替代其属性名（无论多长的名称通过4个byte就可以表示），再根据数字的值，由4个byte压缩成1个或多个byte，同时剔除不必要的元数据信息，达到最佳的序列化性能！<br>　　完整的示例请下载：<a href="/code/serializer-demo.zip">serializer-demo.zip</a></p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://blog.sina.com.cn/s/blog_67d440ab0101hcqe.html" target="_blank" rel="external">http://blog.sina.com.cn/s/blog_67d440ab0101hcqe.html</a><br><a href="http://www.cnblogs.com/liping13599168/archive/2011/06/15/2081366.html" target="_blank" rel="external">http://www.cnblogs.com/liping13599168/archive/2011/06/15/2081366.html</a><br><a href="http://www.cnblogs.com/redcreen/articles/1955307.html" target="_blank" rel="external">http://www.cnblogs.com/redcreen/articles/1955307.html</a><br><a href="http://www.cnblogs.com/xdp-gacl/p/3777987.html" target="_blank" rel="external">http://www.cnblogs.com/xdp-gacl/p/3777987.html</a><br><a href="http://blog.csdn.net/ghsau/article/details/18240731" target="_blank" rel="external">http://blog.csdn.net/ghsau/article/details/18240731</a><br><a href="http://blog.csdn.net/fenglibing/article/details/6859802" target="_blank" rel="external">http://blog.csdn.net/fenglibing/article/details/6859802</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/17/java/10.序列化框架深入分析/" data-id="cijzzpveq00e11cfs3awhgcq4" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/protobuf/">protobuf</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-gis/3.SLD配置示例" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/17/gis/3.SLD配置示例/" class="article-date">
  <time datetime="2016-01-16T18:00:00.000Z" itemprop="datePublished">2016-01-17</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/gis/">gis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/17/gis/3.SLD配置示例/">SLD配置示例</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u70B9_u7EBF_u9762_u914D_u7F6E_u793A_u4F8B"><a href="#u70B9_u7EBF_u9762_u914D_u7F6E_u793A_u4F8B" class="headerlink" title="点线面配置示例"></a>点线面配置示例</h2><p>　　<a href="/code/geoconpoint.sld">geoconpoint.sld</a>，<a href="/code/gnss.sld">gnss.sld</a>，<a href="/code/levelline.sld">levelline.sld</a></p>
<h2 id="u53C2_u8003_u8D44_u6599"><a href="#u53C2_u8003_u8D44_u6599" class="headerlink" title="参考资料"></a>参考资料</h2><p><a href="http://schemas.opengis.net/" target="_blank" rel="external">http://schemas.opengis.net/</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/17/gis/3.SLD配置示例/" data-id="cijzzpvfq00f71cfsjf1wc2jq" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/sld/">sld</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-netty/1.Netty系列之简介" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/17/netty/1.Netty系列之简介/" class="article-date">
  <time datetime="2016-01-16T17:00:00.000Z" itemprop="datePublished">2016-01-17</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/netty/">netty</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/17/netty/1.Netty系列之简介/">Netty系列一之简介</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u5B89_u88C5"><a href="#u5B89_u88C5" class="headerlink" title="安装"></a>安装</h2><p>``` </p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/17/netty/1.Netty系列之简介/" data-id="cijzzpv8g006x1cfs1i2rjppl" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/netty/">netty</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/11.zbus消息存储机制" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/15/java/11.zbus消息存储机制/" class="article-date">
  <time datetime="2016-01-15T06:09:00.000Z" itemprop="datePublished">2016-01-15</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/15/java/11.zbus消息存储机制/">zbus消息存储机制</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u80CC_u666F"><a href="#u80CC_u666F" class="headerlink" title="背景"></a>背景</h2><p>　　目前消息队列产品，如rabbtimq、activemq和zbus等广泛用于各大业务系统，为避免消息队列系统崩溃时，出现消息丢失的情况，需要对消息进行持久化操作，以保证系统的可靠运行！既然要对消息进行持久化操作，那么其实现机制是什么呢？如何保证高效稳定？下面我们看看oschina上的开源项目zbus的实现机制，理解其核心原理！后来发现，zbus的作者在源码中指出其持久化实现原理参考了<a href="http://my.oschina.net/xnkl/blog/477690?fromerr=Gr7v5nwR" target="_blank" rel="external">用mappedbytebuffer实现一个持久化队列</a>。也与高性能队列Fqueue的实现类似。下面我们简单说说它的机制！</p>
<h2 id="u601D_u8DEF"><a href="#u601D_u8DEF" class="headerlink" title="思路"></a>思路</h2><p>　　我们先看看网上的一张图：<img src="/images/zbus-queue-persist.png" alt="zbus-queue-persist.png"><br>　　上图就是队列的文件系统，它包含两个部分：索引(index)文件和数据(block)文件。index文件记录了队列当前的读写文件号，读写位置和读写计数。队列的size是通过读写计数writeCounter-readCounter的方式记录的，这样做的好处是可以做到读写分离。运行时size用一个AtomicInteger变量记录，系统初始化加载队列时才用到读写计数差。<br>　　block（数据）文件记录了实际的入队数据，每个block必须要有足够的空间写入4(len)+data.length+4(EOF)长度的数据，否则写入一个EOF标记，换一个新的block开始写入数据，而当读取到这个EOF时，表示这个block读取完毕，载入下一个block，如果有的话，释放并准备删除当前block。默认规定的block大小32MB。</p>
<h2 id="u5B9E_u73B0"><a href="#u5B9E_u73B0" class="headerlink" title="实现"></a>实现</h2><p>　　在zbus中负责队列持久化的类为：org.zbus.mq.server.support.DiskQueuePool。对照上图，我们在DiskQueuePool可以找到索引文件和数据文件对应的内部类，分别为：DiskQueueIndex和DiskQueueBlock。我们先看看这两个内部类的实现</p>
<h2 id="DiskQueueIndex"><a href="#DiskQueueIndex" class="headerlink" title="DiskQueueIndex"></a>DiskQueueIndex</h2><p>　　我们先看看DiskQueueIndex的关键代码，可以发现，作者通过两个MappedByteBuffer类型的writeIndex和readIndex，实现了索引文件的读写分析。每次初始化DiskQueueIndex时，都要读取该索引文件，获取数据文件和消息的读写位置等元数据信息。如果没有，则创建索引文件。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br></pre></td><td class="code"><pre><span class="line">  <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">DiskQueueIndex</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String MAGIC = <span class="string">"v100"</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String INDEX_FILE_SUFFIX = <span class="string">".idx"</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> INDEX_SIZE = <span class="number">32</span>;</span><br><span class="line">      </span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> FLAG_OFFSET = <span class="number">4</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> READ_NUM_OFFSET = <span class="number">8</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> READ_POS_OFFSET = <span class="number">12</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> READ_CNT_OFFSET = <span class="number">16</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> WRITE_NUM_OFFSET = <span class="number">20</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> WRITE_POS_OFFSET = <span class="number">24</span>;</span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> WRITE_CNT_OFFSET = <span class="number">28</span>;</span><br><span class="line"> </span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">int</span> flag;</span><br><span class="line">      </span><br><span class="line">      <span class="annotation">@SuppressWarnings</span>(<span class="string">"unused"</span>)</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> p11, p12, p13, p14, p15, p16, p17, p18; <span class="comment">// 缓存行填充 32B</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> readPosition;   <span class="comment">// 12   读索引位置</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> readNum;        <span class="comment">// 8   读索引文件号</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> readCounter;    <span class="comment">// 16   总读取数量</span></span><br><span class="line">      </span><br><span class="line">      <span class="annotation">@SuppressWarnings</span>(<span class="string">"unused"</span>)</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> p21, p22, p23, p24, p25, p26, p27, p28; <span class="comment">// 缓存行填充 32B</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> writePosition;  <span class="comment">// 24  写索引位置</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> writeNum;       <span class="comment">// 20  写索引文件号</span></span><br><span class="line">      <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> writeCounter;   <span class="comment">// 28 总写入数量</span></span><br><span class="line">  </span><br><span class="line">      <span class="annotation">@SuppressWarnings</span>(<span class="string">"unused"</span>)</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> p31, p32, p33, p34, p35, p36, p37, p38; <span class="comment">// 缓存行填充 32B</span></span><br><span class="line"> </span><br><span class="line">      <span class="keyword">private</span> RandomAccessFile indexFile;</span><br><span class="line">      <span class="keyword">private</span> FileChannel fileChannel;</span><br><span class="line">      <span class="comment">// 读写分离</span></span><br><span class="line">      <span class="keyword">private</span> MappedByteBuffer writeIndex;</span><br><span class="line">      <span class="keyword">private</span> MappedByteBuffer readIndex;</span><br><span class="line">       </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="title">DiskQueueIndex</span><span class="params">(String indexFilePath)</span> </span>&#123; </span><br><span class="line">          File file = <span class="keyword">new</span> File(indexFilePath);</span><br><span class="line">          <span class="keyword">try</span> &#123;</span><br><span class="line">              <span class="keyword">if</span> (file.exists()) &#123;</span><br><span class="line">                  <span class="keyword">this</span>.indexFile = <span class="keyword">new</span> RandomAccessFile(file, <span class="string">"rw"</span>);</span><br><span class="line">                  <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">4</span>];</span><br><span class="line">                  <span class="keyword">this</span>.indexFile.read(bytes, <span class="number">0</span>, <span class="number">4</span>);</span><br><span class="line">                  <span class="keyword">if</span> (!MAGIC.equals(<span class="keyword">new</span> String(bytes))) &#123;</span><br><span class="line">                      <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"version mismatch"</span>);</span><br><span class="line">                  &#125;</span><br><span class="line">                  <span class="keyword">this</span>.flag = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.readNum = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.readPosition = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.readCounter = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.writeNum = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.writePosition = indexFile.readInt();</span><br><span class="line">                  <span class="keyword">this</span>.writeCounter = indexFile.readInt();</span><br><span class="line">                  </span><br><span class="line">                  <span class="keyword">this</span>.fileChannel = indexFile.getChannel();</span><br><span class="line">                  <span class="keyword">this</span>.writeIndex = fileChannel.map(FileChannel.MapMode.READ_WRITE, <span class="number">0</span>, INDEX_SIZE);</span><br><span class="line">                  <span class="keyword">this</span>.writeIndex = writeIndex.load();</span><br><span class="line">                  <span class="keyword">this</span>.readIndex = (MappedByteBuffer) writeIndex.duplicate();</span><br><span class="line">              &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                  <span class="keyword">this</span>.indexFile = <span class="keyword">new</span> RandomAccessFile(file, <span class="string">"rw"</span>);</span><br><span class="line">                  <span class="keyword">this</span>.fileChannel = indexFile.getChannel();</span><br><span class="line">                  <span class="keyword">this</span>.writeIndex = fileChannel.map(FileChannel.MapMode.READ_WRITE, <span class="number">0</span>, INDEX_SIZE);</span><br><span class="line">                  <span class="keyword">this</span>.readIndex = (MappedByteBuffer) writeIndex.duplicate();</span><br><span class="line">                  putMagic();</span><br><span class="line">                  putFlag(<span class="number">0</span>);</span><br><span class="line">                  putReadNum(<span class="number">0</span>);</span><br><span class="line">                  putReadPosition(<span class="number">0</span>);</span><br><span class="line">                  putReadCounter(<span class="number">0</span>);</span><br><span class="line">                  putWriteNum(<span class="number">0</span>);</span><br><span class="line">                  putWritePosition(<span class="number">0</span>);</span><br><span class="line">                  putWriteCounter(<span class="number">0</span>);</span><br><span class="line">              &#125;</span><br><span class="line">          &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">              <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(e);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isIndexFile</span><span class="params">(String fileName)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> fileName.endsWith(INDEX_FILE_SUFFIX);</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">parseQueueName</span><span class="params">(String indexFileName)</span> </span>&#123;</span><br><span class="line">          String fileName = indexFileName.substring(<span class="number">0</span>, indexFileName.lastIndexOf(<span class="string">'.'</span>));</span><br><span class="line">          <span class="keyword">return</span> fileName;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">formatIndexFilePath</span><span class="params">(String queueName, String fileBackupDir)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> fileBackupDir + File.separator + String.format(<span class="string">"%s%s"</span>, queueName, INDEX_FILE_SUFFIX);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//省略属性对应的get方法</span></span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putMagic</span><span class="params">()</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.position(<span class="number">0</span>);</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.put(MAGIC.getBytes());</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putFlag</span><span class="params">(<span class="keyword">int</span> flag)</span></span>&#123;</span><br><span class="line">      	<span class="keyword">this</span>.writeIndex.position(FLAG_OFFSET);</span><br><span class="line">      	<span class="keyword">this</span>.writeIndex.putInt(flag);</span><br><span class="line">      	<span class="keyword">this</span>.flag = flag;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putWritePosition</span><span class="params">(<span class="keyword">int</span> writePosition)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.position(WRITE_POS_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.putInt(writePosition);</span><br><span class="line">          <span class="keyword">this</span>.writePosition = writePosition;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putWriteNum</span><span class="params">(<span class="keyword">int</span> writeNum)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.position(WRITE_NUM_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.putInt(writeNum);</span><br><span class="line">          <span class="keyword">this</span>.writeNum = writeNum;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putWriteCounter</span><span class="params">(<span class="keyword">int</span> writeCounter)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.position(WRITE_CNT_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.writeIndex.putInt(writeCounter);</span><br><span class="line">          <span class="keyword">this</span>.writeCounter = writeCounter;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putReadNum</span><span class="params">(<span class="keyword">int</span> readNum)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.readIndex.position(READ_NUM_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.readIndex.putInt(readNum);</span><br><span class="line">          <span class="keyword">this</span>.readNum = readNum;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putReadPosition</span><span class="params">(<span class="keyword">int</span> readPosition)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.readIndex.position(READ_POS_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.readIndex.putInt(readPosition);</span><br><span class="line">          <span class="keyword">this</span>.readPosition = readPosition;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putReadCounter</span><span class="params">(<span class="keyword">int</span> readCounter)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">this</span>.readIndex.position(READ_CNT_OFFSET);</span><br><span class="line">          <span class="keyword">this</span>.readIndex.putInt(readCounter);</span><br><span class="line">          <span class="keyword">this</span>.readCounter = readCounter;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">reset</span><span class="params">()</span> </span>&#123;</span><br><span class="line">          <span class="keyword">int</span> size = writeCounter - readCounter;</span><br><span class="line">          putReadCounter(<span class="number">0</span>);</span><br><span class="line">          putWriteCounter(size);</span><br><span class="line">          <span class="keyword">if</span> (size == <span class="number">0</span> &amp;&amp; readNum == writeNum) &#123;</span><br><span class="line">              putReadPosition(<span class="number">0</span>);</span><br><span class="line">              putWritePosition(<span class="number">0</span>);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sync</span><span class="params">()</span> </span>&#123;</span><br><span class="line">          <span class="keyword">if</span> (writeIndex != <span class="keyword">null</span>) &#123;</span><br><span class="line">              writeIndex.force();</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line"> </span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> </span>&#123;</span><br><span class="line">          <span class="keyword">try</span> &#123;</span><br><span class="line">              <span class="keyword">if</span> (writeIndex == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="keyword">return</span>;</span><br><span class="line">              &#125;</span><br><span class="line">              sync();</span><br><span class="line">              AccessController.doPrivileged(<span class="keyword">new</span> PrivilegedAction&lt;Object&gt;() &#123;</span><br><span class="line">              	<span class="annotation">@SuppressWarnings</span>(<span class="string">"restriction"</span>)</span><br><span class="line">                  <span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                      <span class="keyword">try</span> &#123;</span><br><span class="line">                          Method getCleanerMethod = writeIndex.getClass().getMethod(<span class="string">"cleaner"</span>);</span><br><span class="line">                          getCleanerMethod.setAccessible(<span class="keyword">true</span>); </span><br><span class="line">					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(writeIndex);</span><br><span class="line">                          cleaner.clean();</span><br><span class="line">                      &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                          log.error(<span class="string">"close fqueue index file failed"</span>, e);</span><br><span class="line">                      &#125;</span><br><span class="line">                      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                  &#125;</span><br><span class="line">              &#125;);</span><br><span class="line">              writeIndex = <span class="keyword">null</span>;</span><br><span class="line">              readIndex = <span class="keyword">null</span>;</span><br><span class="line">              fileChannel.close();</span><br><span class="line">              indexFile.close();</span><br><span class="line">          &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">              log.error(<span class="string">"close fqueue index file failed"</span>, e);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="DiskQueueBlock"><a href="#DiskQueueBlock" class="headerlink" title="DiskQueueBlock"></a>DiskQueueBlock</h2><p>　　下面我们看看DiskQueueBlock的关键代码。可以发现，文件的结束标志EOF取值为-1。每次通过write和read方法读写消息时，都要更新对应的索引文件。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">DiskQueueBlock</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String BLOCK_FILE_SUFFIX = <span class="string">".blk"</span>; <span class="comment">// 数据文件</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> BLOCK_SIZE = <span class="number">32</span> * <span class="number">1024</span> * <span class="number">1024</span>; <span class="comment">// 32MB</span></span><br><span class="line"> </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> EOF = -<span class="number">1</span>;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">private</span> String blockFilePath;</span><br><span class="line">    <span class="keyword">private</span> DiskQueueIndex index;</span><br><span class="line">    <span class="keyword">private</span> RandomAccessFile blockFile;</span><br><span class="line">    <span class="keyword">private</span> FileChannel fileChannel;</span><br><span class="line">    <span class="keyword">private</span> ByteBuffer byteBuffer;</span><br><span class="line">    <span class="keyword">private</span> MappedByteBuffer mappedBlock;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DiskQueueBlock</span><span class="params">(String blockFilePath, DiskQueueIndex index, RandomAccessFile blockFile, FileChannel fileChannel,</span><br><span class="line">                        ByteBuffer byteBuffer, MappedByteBuffer mappedBlock)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.blockFilePath = blockFilePath;</span><br><span class="line">        <span class="keyword">this</span>.index = index;</span><br><span class="line">        <span class="keyword">this</span>.blockFile = blockFile;</span><br><span class="line">        <span class="keyword">this</span>.fileChannel = fileChannel;</span><br><span class="line">        <span class="keyword">this</span>.byteBuffer = byteBuffer;</span><br><span class="line">        <span class="keyword">this</span>.mappedBlock = mappedBlock;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DiskQueueBlock</span><span class="params">(DiskQueueIndex index, String blockFilePath)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.index = index;</span><br><span class="line">        <span class="keyword">this</span>.blockFilePath = blockFilePath;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            File file = <span class="keyword">new</span> File(blockFilePath);</span><br><span class="line">            <span class="keyword">this</span>.blockFile = <span class="keyword">new</span> RandomAccessFile(file, <span class="string">"rw"</span>);</span><br><span class="line">            <span class="keyword">this</span>.fileChannel = blockFile.getChannel();</span><br><span class="line">            <span class="keyword">this</span>.mappedBlock = fileChannel.map(FileChannel.MapMode.READ_WRITE, <span class="number">0</span>, BLOCK_SIZE);</span><br><span class="line">            <span class="keyword">this</span>.byteBuffer = mappedBlock.load();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> DiskQueueBlock <span class="title">duplicate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DiskQueueBlock(<span class="keyword">this</span>.blockFilePath, <span class="keyword">this</span>.index, <span class="keyword">this</span>.blockFile, <span class="keyword">this</span>.fileChannel,</span><br><span class="line">                <span class="keyword">this</span>.byteBuffer.duplicate(), <span class="keyword">this</span>.mappedBlock);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">formatBlockFilePath</span><span class="params">(String queueName, <span class="keyword">int</span> fileNum, String fileBackupDir)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fileBackupDir + File.separator + String.format(<span class="string">"%s_%d%s"</span>, queueName, fileNum, BLOCK_FILE_SUFFIX);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getBlockFilePath</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> blockFilePath;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putEOF</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.byteBuffer.position(index.getWritePosition());</span><br><span class="line">        <span class="keyword">this</span>.byteBuffer.putInt(EOF);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSpaceAvailable</span><span class="params">(<span class="keyword">int</span> len)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> increment = len + <span class="number">4</span>;</span><br><span class="line">        <span class="keyword">int</span> writePosition = index.getWritePosition();</span><br><span class="line">        <span class="keyword">return</span> BLOCK_SIZE &gt;= increment + writePosition + <span class="number">4</span>; <span class="comment">// 保证最后有4字节的空间可以写入EOF</span></span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">eof</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> readPosition = index.getReadPosition();</span><br><span class="line">        <span class="keyword">return</span> readPosition &gt; <span class="number">0</span> &amp;&amp; byteBuffer.getInt(readPosition) == EOF;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">write</span><span class="params">(<span class="keyword">byte</span>[] bytes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> len = bytes.length;</span><br><span class="line">        <span class="keyword">int</span> increment = len + <span class="number">4</span>;</span><br><span class="line">        <span class="keyword">int</span> writePosition = index.getWritePosition();</span><br><span class="line">        byteBuffer.position(writePosition);</span><br><span class="line">        byteBuffer.putInt(len);</span><br><span class="line">        byteBuffer.put(bytes);</span><br><span class="line">        index.putWritePosition(increment + writePosition);</span><br><span class="line">        index.putWriteCounter(index.getWriteCounter() + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">return</span> increment;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">write</span><span class="params">(<span class="keyword">byte</span>[] bytes, <span class="keyword">int</span> start, <span class="keyword">int</span> len)</span> </span>&#123; </span><br><span class="line">        <span class="keyword">int</span> increment = len + <span class="number">4</span>;</span><br><span class="line">        <span class="keyword">int</span> writePosition = index.getWritePosition();</span><br><span class="line">        byteBuffer.position(writePosition);</span><br><span class="line">        byteBuffer.putInt(len); </span><br><span class="line">        byteBuffer.put(bytes, start, len);</span><br><span class="line">        index.putWritePosition(increment + writePosition);</span><br><span class="line">        index.putWriteCounter(index.getWriteCounter() + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">return</span> increment;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] read() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] bytes;</span><br><span class="line">        <span class="keyword">int</span> readNum = index.getReadNum();</span><br><span class="line">        <span class="keyword">int</span> readPosition = index.getReadPosition();</span><br><span class="line">        <span class="keyword">int</span> writeNum = index.getWriteNum();</span><br><span class="line">        <span class="keyword">int</span> writePosition = index.getWritePosition();</span><br><span class="line">        <span class="keyword">if</span> (readNum == writeNum &amp;&amp; readPosition &gt;= writePosition) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        byteBuffer.position(readPosition);</span><br><span class="line">        <span class="keyword">int</span> dataLength = byteBuffer.getInt();</span><br><span class="line">        <span class="keyword">if</span> (dataLength &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[dataLength];</span><br><span class="line">        byteBuffer.get(bytes);</span><br><span class="line">        index.putReadPosition(readPosition + bytes.length + <span class="number">4</span>);</span><br><span class="line">        index.putReadCounter(index.getReadCounter() + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">return</span> bytes;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sync</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (mappedBlock != <span class="keyword">null</span>) &#123;</span><br><span class="line">            mappedBlock.force();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (mappedBlock == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            sync();</span><br><span class="line">            AccessController.doPrivileged(<span class="keyword">new</span> PrivilegedAction&lt;Object&gt;() &#123;</span><br><span class="line">                <span class="annotation">@SuppressWarnings</span>(<span class="string">"restriction"</span>)</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        Method getCleanerMethod = mappedBlock.getClass().getMethod(<span class="string">"cleaner"</span>);</span><br><span class="line">                        getCleanerMethod.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                        sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(mappedBlock);</span><br><span class="line">                        cleaner.clean();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                        log.error(<span class="string">"close fqueue block file failed"</span>, e);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            mappedBlock = <span class="keyword">null</span>;</span><br><span class="line">            byteBuffer = <span class="keyword">null</span>;</span><br><span class="line">            fileChannel.close();</span><br><span class="line">            blockFile.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            log.error(<span class="string">"close fqueue block file failed"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="DiskQueue"><a href="#DiskQueue" class="headerlink" title="DiskQueue"></a>DiskQueue</h2><p>　　接着我们看看另一个内部类DiskQueue，可以将它理解为一个代理类，所有对索引文件和数据文件的操作，都是通过该类提供的方法完成的。初始化该对象时，需要先判断要读取的数据文件和要写入的数据文件是不是同一个数据文件，作者同样实现了数据文件的读写分离。<br>　　这里，作者还提供了两个ReentrantLock类型的读锁和写锁。进行相应的操作时都要加锁，此处会不会造成性能的问题暂时不做测试分析。在进行读写时，都要判断是否需要进入下一个数据文件进行操作。<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br></pre></td><td class="code"><pre><span class="line">public static class DiskQueue extends AbstractQueue&lt;byte[]&gt; &#123;</span><br><span class="line"></span><br><span class="line">    private String queueName;</span><br><span class="line">    private String fileBackupDir;</span><br><span class="line">    private DiskQueueIndex index;</span><br><span class="line">    private DiskQueueBlock readBlock;</span><br><span class="line">    private DiskQueueBlock writeBlock;</span><br><span class="line">    private ReentrantLock readLock;</span><br><span class="line">    private ReentrantLock writeLock;</span><br><span class="line">    private AtomicInteger size;</span><br><span class="line"></span><br><span class="line">    public DiskQueue(String queueName, String fileBackupDir) &#123;</span><br><span class="line">        this.queueName = queueName;</span><br><span class="line">        this.fileBackupDir = fileBackupDir;</span><br><span class="line">        this.readLock = new ReentrantLock();</span><br><span class="line">        this.writeLock = new ReentrantLock();</span><br><span class="line">        this.index = new DiskQueueIndex(DiskQueueIndex.formatIndexFilePath(queueName, fileBackupDir));</span><br><span class="line">        this.size = new AtomicInteger(index.getWriteCounter() - index.getReadCounter());</span><br><span class="line">        this.writeBlock = new DiskQueueBlock(index, DiskQueueBlock.formatBlockFilePath(queueName,</span><br><span class="line">                index.getWriteNum(), fileBackupDir));</span><br><span class="line">        if (index.getReadNum() == index.getWriteNum()) &#123;</span><br><span class="line">            this.readBlock = this.writeBlock.duplicate();</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            this.readBlock = new DiskQueueBlock(index, DiskQueueBlock.formatBlockFilePath(queueName,</span><br><span class="line">                    index.getReadNum(), fileBackupDir));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    public int getFlag()&#123;</span><br><span class="line">    	return index.getFlag();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    public void setFlag(int flag)&#123;</span><br><span class="line">    	index.putFlag(flag);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Iterator&lt;byte[]&gt; iterator() &#123;</span><br><span class="line">        throw new UnsupportedOperationException();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public int size() &#123;</span><br><span class="line">        return this.size.get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private void rotateNextWriteBlock() &#123;</span><br><span class="line">        int nextWriteBlockNum = index.getWriteNum() + 1;</span><br><span class="line">        nextWriteBlockNum = (nextWriteBlockNum &lt; 0) ? 0 : nextWriteBlockNum;</span><br><span class="line">        writeBlock.putEOF();</span><br><span class="line">        if (index.getReadNum() == index.getWriteNum()) &#123;</span><br><span class="line">            writeBlock.sync();</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            writeBlock.close();</span><br><span class="line">        &#125;</span><br><span class="line">        writeBlock = new DiskQueueBlock(index, DiskQueueBlock.formatBlockFilePath(queueName,</span><br><span class="line">                nextWriteBlockNum, fileBackupDir));</span><br><span class="line">        index.putWriteNum(nextWriteBlockNum);</span><br><span class="line">        index.putWritePosition(0);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean offer(byte[] bytes) &#123;</span><br><span class="line">        if (bytes == null || bytes.length == 0) &#123;</span><br><span class="line">            return true;</span><br><span class="line">        &#125;</span><br><span class="line">        writeLock.lock();</span><br><span class="line">        try &#123;</span><br><span class="line">            if (!writeBlock.isSpaceAvailable(bytes.length)) &#123;</span><br><span class="line">                rotateNextWriteBlock();</span><br><span class="line">            &#125;</span><br><span class="line">            writeBlock.write(bytes);</span><br><span class="line">            size.incrementAndGet();</span><br><span class="line">            return true;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            writeLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private void rotateNextReadBlock() &#123;</span><br><span class="line">        if (index.getReadNum() == index.getWriteNum()) &#123;</span><br><span class="line">            // 读缓存块的滑动必须发生在写缓存块滑动之后</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        int nextReadBlockNum = index.getReadNum() + 1;</span><br><span class="line">        nextReadBlockNum = (nextReadBlockNum &lt; 0) ? 0 : nextReadBlockNum;</span><br><span class="line">        readBlock.close();</span><br><span class="line">        String blockPath = readBlock.getBlockFilePath();</span><br><span class="line">        if (nextReadBlockNum == index.getWriteNum()) &#123;</span><br><span class="line">            readBlock = writeBlock.duplicate();</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            readBlock = new DiskQueueBlock(index, DiskQueueBlock.formatBlockFilePath(queueName,</span><br><span class="line">                    nextReadBlockNum, fileBackupDir));</span><br><span class="line">        &#125;</span><br><span class="line">        index.putReadNum(nextReadBlockNum);</span><br><span class="line">        index.putReadPosition(0);</span><br><span class="line">        DiskQueuePool.toClear(blockPath);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public byte[] poll() &#123;</span><br><span class="line">        readLock.lock();</span><br><span class="line">        try &#123;</span><br><span class="line">            if (readBlock.eof()) &#123;</span><br><span class="line">                rotateNextReadBlock();</span><br><span class="line">            &#125;</span><br><span class="line">            byte[] bytes = readBlock.read();</span><br><span class="line">            if (bytes != null) &#123;</span><br><span class="line">                size.decrementAndGet();</span><br><span class="line">            &#125;</span><br><span class="line">            return bytes;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            readLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public byte[] peek() &#123;</span><br><span class="line">        throw new UnsupportedOperationException();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void sync() &#123;</span><br><span class="line">        index.sync();</span><br><span class="line">        // read block只读，不用同步</span><br><span class="line">        writeBlock.sync();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void close() &#123;</span><br><span class="line">        writeBlock.close();</span><br><span class="line">        if (index.getReadNum() != index.getWriteNum()) &#123;</span><br><span class="line">            readBlock.close();</span><br><span class="line">        &#125;</span><br><span class="line">        index.reset();</span><br><span class="line">        index.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="DiskQueuePool"><a href="#DiskQueuePool" class="headerlink" title="DiskQueuePool"></a>DiskQueuePool</h2><p>　　最后我们看看线程池的实现机制。初始化该类时，都会先调用scanDir方法将离线的队列文件加载，每个队列都会单独对应一个的索引文件和多个数据文件。之后会初始化一个ScheduledExecutorService类型的定时任务，每隔10秒钟，调用索引文件和数据文件的mappedbytebuffer的force，将数据刷入磁盘！<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> BlockingQueue&lt;String&gt; deletingQueue = <span class="keyword">new</span> LinkedBlockingQueue&lt;String&gt;();</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> DiskQueuePool instance = <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">private</span> String fileBackupPath;</span><br><span class="line"><span class="keyword">private</span> Map&lt;String, DiskQueue&gt; queueMap;</span><br><span class="line"><span class="keyword">private</span> ScheduledExecutorService syncService;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">DiskQueuePool</span><span class="params">(String fileBackupPath)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.fileBackupPath = fileBackupPath;</span><br><span class="line">    File fileBackupDir = <span class="keyword">new</span> File(fileBackupPath);</span><br><span class="line">    <span class="keyword">if</span> (!fileBackupDir.exists() &amp;&amp; !fileBackupDir.mkdir()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"can not create directory"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.queueMap = scanDir(fileBackupDir);</span><br><span class="line">    <span class="keyword">this</span>.syncService = Executors.newSingleThreadScheduledExecutor();</span><br><span class="line">    <span class="keyword">this</span>.syncService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">        <span class="annotation">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">for</span> (DiskQueue q : queueMap.values()) &#123;</span><br><span class="line">                q.sync();</span><br><span class="line">            &#125;</span><br><span class="line">            deleteBlockFile();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="number">1000</span>, <span class="number">10000</span>, TimeUnit.MILLISECONDS);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Map&lt;String, DiskQueue&gt; getQueryMap()&#123;</span><br><span class="line">	<span class="keyword">return</span> instance.queueMap;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">deleteBlockFile</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    String blockFilePath = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">while</span>( (blockFilePath = deletingQueue.poll()) != <span class="keyword">null</span>)&#123;</span><br><span class="line">    	blockFilePath = blockFilePath.trim();</span><br><span class="line">    	<span class="keyword">if</span>(blockFilePath.equals(<span class="string">""</span>)) <span class="keyword">continue</span>;</span><br><span class="line">    	log.info(<span class="string">"Delete File[%s]"</span>, blockFilePath);   </span><br><span class="line">        File delFile = <span class="keyword">new</span> File(blockFilePath);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!delFile.delete()) &#123;</span><br><span class="line">                log.warn(<span class="string">"block file:%s delete failed"</span>, blockFilePath);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SecurityException e) &#123;</span><br><span class="line">            log.error(<span class="string">"security manager exists, delete denied"</span>);</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">toClear</span><span class="params">(String filePath)</span> </span>&#123;</span><br><span class="line">    deletingQueue.add(filePath);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">private</span> Map&lt;String, DiskQueue&gt; scanDir(File fileBackupDir) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!fileBackupDir.isDirectory()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"it is not a directory"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    Map&lt;String, DiskQueue&gt; queues = <span class="keyword">new</span> HashMap&lt;String, DiskQueue&gt;();</span><br><span class="line">    File[] indexFiles = fileBackupDir.listFiles(<span class="keyword">new</span> FilenameFilter() &#123;</span><br><span class="line">        <span class="annotation">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">accept</span><span class="params">(File dir, String name)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> DiskQueueIndex.isIndexFile(name);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">if</span> (indexFiles != <span class="keyword">null</span> &amp;&amp; indexFiles.length&gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (File indexFile : indexFiles) &#123;</span><br><span class="line">            String queueName = DiskQueueIndex.parseQueueName(indexFile.getName());</span><br><span class="line">            queues.put(queueName, <span class="keyword">new</span> DiskQueue(queueName, fileBackupPath));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> queues;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(String deployPath)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (instance == <span class="keyword">null</span>) &#123;</span><br><span class="line">        instance = <span class="keyword">new</span> DiskQueuePool(deployPath);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.syncService.shutdown();</span><br><span class="line">    <span class="keyword">for</span> (DiskQueue q : queueMap.values()) &#123;</span><br><span class="line">        q.close();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (!deletingQueue.isEmpty()) &#123;</span><br><span class="line">        deleteBlockFile();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">destory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (instance != <span class="keyword">null</span>) &#123;</span><br><span class="line">        instance.dispose();</span><br><span class="line">        instance = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">private</span> DiskQueue <span class="title">getQueueFromPool</span><span class="params">(String queueName)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (queueMap.containsKey(queueName)) &#123;</span><br><span class="line">        <span class="keyword">return</span> queueMap.get(queueName);</span><br><span class="line">    &#125;</span><br><span class="line">    DiskQueue q = <span class="keyword">new</span> DiskQueue(queueName, fileBackupPath);</span><br><span class="line">    queueMap.put(queueName, q);</span><br><span class="line">    <span class="keyword">return</span> q;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> DiskQueue <span class="title">getDiskQueue</span><span class="params">(String queueName)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(instance == <span class="keyword">null</span>)&#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"call DiskQueuePool.init(dir) first"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="keyword">if</span> (queueName==<span class="keyword">null</span> || queueName.trim().equals(<span class="string">""</span>)) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"empty queue name"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> instance.getQueueFromPool(queueName);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　为保证消息持久化的性能，作者主要采取了以下几种机制：<br>　　1. 采用MappedByteBuffer实现高效的文件读写<br>　　2. 采用读写分离的机制实现磁盘的顺序读写，保证效率<br>　　3. 对数据文件分块，每块32M，方便迁移和维护<br>　　4. 每个队列独立存储，包含一个索引文件和多个数据文件，避免队列之间的相互影响</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://my.oschina.net/xnkl/blog/477690?fromerr=Gr7v5nwR" target="_blank" rel="external">http://my.oschina.net/xnkl/blog/477690?fromerr=Gr7v5nwR</a><br><a href="http://git.oschina.net/rushmore/zbus" target="_blank" rel="external">http://git.oschina.net/rushmore/zbus</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/15/java/11.zbus消息存储机制/" data-id="cijzzpvem00dx1cfsx1hkessv" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/zbus/">zbus</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/12.分布式事物" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/14/java/12.分布式事物/" class="article-date">
  <time datetime="2016-01-14T06:10:00.000Z" itemprop="datePublished">2016-01-14</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/14/java/12.分布式事物/">分布式事务</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u80CC_u666F"><a href="#u80CC_u666F" class="headerlink" title="背景"></a>背景</h2><p>　　<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"> </span><br></pre></td></tr></table></figure></p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/14/java/12.分布式事物/" data-id="cijzzpvei00dt1cfsq163sz6x" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/transaction/">transaction</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-网页推送" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/13/网页推送/" class="article-date">
  <time datetime="2016-01-13T04:21:36.000Z" itemprop="datePublished">2016-01-13</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/java/">java</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/13/网页推送/">网页推送技术</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　除了移动终端的消息推送能力，我们还经常遇到网页版的消息推送或即时通信的能力。考虑到跨浏览器兼容性的问题，很多新的特性，比如websocket、sse等需要慎重使用！这篇文章我们将简单介绍一下服务端向浏览器推送消息的技术方案</p>
<h2 id="SSE"><a href="#SSE" class="headerlink" title="SSE"></a>SSE</h2><p>　　SSE（Server-Sent Event，服务端推送事件）是一种允许服务端向客户端推送新数据的HTML5技术。与WebSocket相比，SSE最大的优势就是：不需要添加任何新组件，用任何你习惯的后端语言和框架就能继续使用。<br>　　采用java+tomcat开发，我们只需要实现一个HttpServlet，并调用HttpServletResponse.setContentType(“text/event-stream”)就行了，非常容易（详见文章后面是的示例代码）！但是实测却发现了两个非常奇葩的问题：1. 首次推送数据后，会自动周期性的（约3秒左右）向浏览器发送前一次发送的数据。2. 关闭浏览器，服务端无法检测到行为，仍然继续推送数据，没有任何错误产生。实测在nodejs中没有这些问题！<br>　　相比较WebSocket的二进制协议，SSE的协议非常的简单，服务端断开连接命令格式：(“event: close\n”) 服务端发送数据命令格式：(“data: “ + msg + “\n\n”)。</p>
<h2 id="WebSocket"><a href="#WebSocket" class="headerlink" title="WebSocket"></a>WebSocket</h2><p>　　WebSocket是一种更为复杂的服务端实现技术，但它是真正的双向传输技术，<strong>既能从服务端向客户端推送数据，也能从客户端向服务端推送数据</strong>。WebSocket和SSE的浏览器支持率差不多，大多数主流桌面浏览器两者都支持，Android 4.4中，系统默认浏览器两者都支持。IE是个例外，即便IE11都还不支持原生SSE，IE10添加了WebSocket支持。</p>
<h2 id="Socket-IO"><a href="#Socket-IO" class="headerlink" title="Socket.IO"></a>Socket.IO</h2><p>　　Socket.IO是一个开源的WebSocket库，它通过Node.js实现WebSocket服务端，同时也提供客户端JS库。Socket.IO支持以事件为基础的实时双向通讯，它可以工作在任何平台、浏览器或移动设备。并支持4种协议：WebSocket、htmlfile、xhr-polling、jsonp-polling，它会自动根据浏览器选择适合的通讯方式，从而让开发者可以聚焦到功能的实现而不是平台的兼容性，同时Socket.IO具有不错的稳定性和性能。</p>
<h2 id="Comet"><a href="#Comet" class="headerlink" title="Comet"></a>Comet</h2><p>　　待补充</p>
<h2 id="Pushlet"><a href="#Pushlet" class="headerlink" title="Pushlet"></a>Pushlet</h2><p>　　待补充</p>
<h2 id="Jersey"><a href="#Jersey" class="headerlink" title="Jersey"></a>Jersey</h2><p>　　待补充</p>
<p>　　SSE示例下载地址：<a href="/code/push-sse.rar">push-sse.rar</a></p>
<h2 id="u53C2_u8003_u8FDE_u63A5"><a href="#u53C2_u8003_u8FDE_u63A5" class="headerlink" title="参考连接"></a>参考连接</h2><p><a href="http://www.plhwin.com/2014/05/28/nodejs-socketio/" target="_blank" rel="external">http://www.plhwin.com/2014/05/28/nodejs-socketio/</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/13/网页推送/" data-id="cijzzpv0f00091cfs6ew4bv43" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/push/">push</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/web/">web</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-gis/2.地图投影" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/13/gis/2.地图投影/" class="article-date">
  <time datetime="2016-01-13T04:21:36.000Z" itemprop="datePublished">2016-01-13</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/gis/">gis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/13/gis/2.地图投影/">Google Maps地图投影全解析</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　Google Maps、Virtual Earth等网络地理所使用的地图投影，常被称作Web Mercator或Spherical Mercator，它与常规墨卡托投影的主要区别就是把地球模拟为球体而非椭球体。</p>
<h2 id="u58A8_u5361_u6258_u6295_u5F71"><a href="#u58A8_u5361_u6258_u6295_u5F71" class="headerlink" title="墨卡托投影"></a>墨卡托投影</h2><p>　　墨卡托(Mercator)投影，又名“等角正轴圆柱投影”，荷兰地图学家墨卡托（Mercator）在1569年拟定，假设地球被围在一个中空的圆柱里，其赤道与圆柱相接触，然后再假想地球中心有一盏灯，把球面上的图形投影到圆柱体上，再把圆柱体展开，这就是一幅标准纬线为零度（即赤道）的“墨卡托投影”绘制出的世界地图。从球到平面，有个转换公式，这里就不再罗列</p>
<h2 id="Google_u9009_u62E9_u58A8_u5361_u6258_u6295_u5F71_u539F_u56E0"><a href="#Google_u9009_u62E9_u58A8_u5361_u6258_u6295_u5F71_u539F_u56E0" class="headerlink" title="Google选择墨卡托投影原因"></a>Google选择墨卡托投影原因</h2><p>　　墨卡托投影的“等角”特性，保证了对象的形状的不变行，正方形的物体投影后不会变为长方形。“等角”也保证了方向和相互位置的正确性，因此在航海和航空中常常应用，而Google们在计算人们查询地物的方向时不会出错。<br>　　墨卡托投影的“圆柱”特性，保证了南北（纬线）和东西（经线）都是平行直线，并且相互垂直。而且经线间隔是相同的，纬线间隔从标准纬线（此处是赤道，也可能是其他纬线）向两级逐渐增大。<br>但是，“等角”不可避免的带来的面积的巨大变形，特别是两极地区，明显的如格陵兰岛比实际面积扩大了N倍。不过要是去两极地区探险或科考的同志们，一般有更详细的资料，不会来查看网络地图的，这个不要紧。<img src="/images/5f22f2e219a.jpeg" alt="5f22f2e219a.jpeg"></p>
<h2 id="u5706_u5F62_u7403_u4F53_uFF0C_u975E_u692D_u7403_u4F53"><a href="#u5706_u5F62_u7403_u4F53_uFF0C_u975E_u692D_u7403_u4F53" class="headerlink" title="圆形球体，非椭球体"></a>圆形球体，非椭球体</h2><p>　　仅仅是由于实现的方便和计算上的简单，精度理论上差别0.33%之内，特别是比例尺越大，地物更详细的时候，差别基本可以忽略。</p>
<h2 id="Web_u58A8_u5361_u6258_u6295_u5F71_u5750_u6807_u7CFB"><a href="#Web_u58A8_u5361_u6258_u6295_u5F71_u5750_u6807_u7CFB" class="headerlink" title="Web墨卡托投影坐标系"></a>Web墨卡托投影坐标系</h2><p>　　以整个世界范围，赤道作为标准纬线，本初子午线作为中央经线，两者交点为坐标原点，向东向北为正，向西向南为负。<br>　　X轴：由于赤道半径为6378137米，则赤道周长为2<em>PI</em>r = 2*20037508.3427892，因此X轴的取值范围：[-20037508.3427892,20037508.3427892]。<br>　　Y轴：由墨卡托投影的公式可知，同时上图也有示意，当纬度φ接近两极，即90°时，y值趋向于无穷。这是那些“懒惰的工程师”就把Y轴的取值范围也限定在[-20037508.3427892,20037508.3427892]之间，搞个正方形。<br>　　懒人的好处，众所周知，事先切好静态图片，提高访问效率云云。因此在投影坐标系（米）下的范围是：最小(-20037508.3427892, -20037508.3427892 )到最大 (20037508.3427892, 20037508.3427892)。</p>
<h2 id="u5BF9_u5E94_u7684_u5730_u7406_u5750_u6807_u7CFB_3A"><a href="#u5BF9_u5E94_u7684_u5730_u7406_u5750_u6807_u7CFB_3A" class="headerlink" title="对应的地理坐标系:"></a>对应的地理坐标系:</h2><p>　　按道理，先讲地理坐标系才是，比如球体还是椭球体是地理坐标系的事情，和墨卡托投影本关联不大。简单来说，投影坐标系(PROJCS)是平面坐标系，以米为单位；而地理坐标系(GEOGCS)是椭球面坐标系，以经纬度为单位。<br>　　经度：这边没问题，可取全球范围：[-180,180]。<br>　　纬度：上面已知，纬度不可能到达90°，懒人们为了正方形而取的-20037508.3427892，经过反计算，可得到纬度85.05112877980659。因此纬度取值范围是[-85.05112877980659，85.05112877980659]。其余的地区怎么办？没事，企鹅们不在乎。<br>　　因此，地理坐标系（经纬度）对应的范围是：最小(-180,-85.05112877980659)，最大(180, 85.05112877980659)。至于其中的Datum、坐标转换等就不再多言。</p>
<h2 id="u53C2_u8003_u8FDE_u63A5"><a href="#u53C2_u8003_u8FDE_u63A5" class="headerlink" title="参考连接"></a>参考连接</h2>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/13/gis/2.地图投影/" data-id="cijzzpvft00fb1cfs603b54b1" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/map/">map</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-gis/1.geohash" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/13/gis/1.geohash/" class="article-date">
  <time datetime="2016-01-13T04:21:36.000Z" itemprop="datePublished">2016-01-13</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/gis/">gis</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/13/gis/1.geohash/">Geohash</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　在gis领域中，空间运算操作，比如周边搜索等，服务端实现基本上采用借助于oracle spatial等数据库提供的空间运算能力，直接进行空间计算，得到结果并返回，这种模式在应对互联网高并发的情况下存在一定的性能问题。<br>　　在互联网应用场景下，在很多应用中，并不需要gis专业领域中非常精确地计算结果。同时考虑到国防安全，也不可能直接在互联网上提供高精度的空间数据。在这种情况下，Geohash就横空出世了！</p>
<h2 id="u7279_u70B9"><a href="#u7279_u70B9" class="headerlink" title="特点"></a>特点</h2><p>　　1.  GeoHash将二维的经纬度转换成字符串，比如下图展示了北京9个区域的GeoHash字符串，分别是WX4ER，WX4G2、WX4G3等等，每一个字符串代表了某一矩形区域。也就是说，这个矩形区域内所有的点（经纬度坐标）都共享相同的GeoHash字符串，这样可以保护隐私的同时（只表示大概区域位置而不是具体的点），又比较容易做缓存。比如左上角这个区域内的**WX4ER区域的用户不断发送位置信息请求附近餐馆数据，所以可以把key=WX4ER，value=该区域的餐馆信息进行缓存.而如果不使用GeoHash的话，由于区域内的用户传来的经纬度是各不相同的，很难做缓存。<img src="/images/geohash1.jpg" alt="geohash1.jpg"><br>　　2. 字符串越长，表示的范围越精确。如图所示，5位的编码能表示10平方千米范围的矩形区域，而6位编码能表示更精细的区域（约0.34平方千米）<img src="/images/geohash2.jpg" alt="geohash2.jpg"><br>　　3. 字符串相似的表示距离相近（特殊情况后文阐述），这样可以利用字符串的前缀匹配来查询附近的POI信息。如下两个图所示，一个在城区，一个在郊区，城区的GeoHash字符串之间比较相似，郊区的字符串之间也比较相似，而城区和郊区的GeoHash字符串相似程度要低些。<img src="/images/geohash3.jpg" alt="geohash3.jpg"><br>　　到这里我们可以知道GeoHash就是一种将经纬度转换成字符串的方法，并且使得在大部分情况下，字符串前缀匹配越多的距离越近。根据所在位置查询来查询附近餐馆时，只需要将所在位置经纬度转换成GeoHash字符串，并与各个餐馆的GeoHash字符串进行前缀匹配，匹配越多的距离越近。</p>
<h2 id="u5B9E_u73B0"><a href="#u5B9E_u73B0" class="headerlink" title="实现"></a>实现</h2><p>　　下面以北海公园为例介绍GeoHash算法的计算步骤：<br>　　1. 根据经纬度计算GeoHash二进制编码：地球纬度区间是[-90,90]， 北海公园的纬度是39.928167，可以通过下面算法对纬度39.928167进行逼近编码:<br>　　1）区间[-90,90]进行二分为[-90,0),[0,90]，称为左右区间，可以确定39.928167属于右区间[0,90]，给标记为1；<br>　　2）接着将区间[0,90]进行二分为 [0,45),[45,90]，可以确定39.928167属于左区间 [0,45)，给标记为0；<br>　　3）递归上述过程39.928167总是属于某个区间[a,b]。随着每次迭代区间[a,b]总在缩小，并越来越逼近39.928167；<br>　　4）如果给定的纬度x（39.928167）属于左区间，则记录0，如果属于右区间则记录1，这样随着算法的进行会产生一个序列1011100，序列的长度跟给定的区间划分次数有关。<br>　　根据纬度算编码：<img src="/images/geohash-lat.jpg" alt="geohash-lat.jpg"><br>　　同理，地球经度区间是[-180,180]，可以对经度116.389550进行编码：<img src="/images/geohash-lon.jpg" alt="geohash-lon.jpg"><br>　　2. 组码：通过上述计算，纬度产生的编码为10111 00011，经度产生的编码为11010 01011。偶数位放经度，奇数位放纬度，把2串编码组合生成新串：11100 11101 00100 01111。最后使用0-9、b-z（去掉a, i, l, o）这32个字母进行base32编码，首先将11100 11101 00100 01111转成十进制(每五位为一个单位，最大取值为11111=31)，对应着28、29、4、15，十进制对应的base32编码就是wx4g。同理，将编码转换成经纬度的解码算法与之相反，具体不再赘述。<img src="/images/geohash-base32.jpg" alt="geohash-base32.jpg"></p>
<h2 id="u539F_u7406"><a href="#u539F_u7406" class="headerlink" title="原理"></a>原理</h2><p>　　上文讲了GeoHash的计算步骤，仅仅说明是什么而没有说明为什么？为什么分别给经度和维度编码？为什么需要将经纬度两串编码交叉组合成一串编码？本节试图回答这一问题。<br>　　如图所示，我们将二进制编码的结果填写到空间中，当将空间划分为四块时候，编码的顺序分别是左下角00，左上角01，右下脚10，右上角11，也就是类似于Z的曲线，当我们递归的将各个块分解成更小的子块时，编码的顺序是自相似的（分形），每一个子快也形成Z曲线，这种类型的曲线被称为Peano空间填充曲线。<br>　　这种类型的空间填充曲线的优点是将二维空间转换成一维曲线（事实上是分形维），对大部分而言，编码相似的距离也相近， 但Peano空间填充曲线最大的缺点就是突变性，有些编码相邻但距离却相差很远，比如0111与1000，编码是相邻的，但距离相差很大。<img src="/images/geohash-peano.jpg" alt="geohash-peano.jpg"><br>　　除Peano空间填充曲线外，还有很多空间填充曲线，如图所示，其中效果公认较好是Hilbert空间填充曲线，相较于Peano曲线而言，Hilbert曲线没有较大的突变。为什么GeoHash不选择Hilbert空间填充曲线呢？可能是Peano曲线思路以及计算上比较简单吧，事实上，Peano曲线就是一种四叉树线性编码方式。<img src="/images/geohash-arth.jpg" alt="geohash-arth.jpg"></p>
<h2 id="u7F3A_u70B9"><a href="#u7F3A_u70B9" class="headerlink" title="缺点"></a>缺点</h2><p>　　如果两个点靠的很近，但是被划分到了两个区域，会导致两个点的编码差别比距离更远的点更大，如下图所示：<img src="/images/geohash-bug.jpg" alt="geohash-bug.jpg"><br>　　红色的点是我们的位置，绿色的两个点分别是附近的两个餐馆，但是在查询的时候会发现距离较远餐馆的GeoHash编码与我们一样（因为在同一个GeoHash区域块上），而较近餐馆的GeoHash编码与我们不一致。解决的思路很简单，<strong>除了使用定位点的GeoHash编码进行匹配外，还使用周围8个区域的GeoHash编码</strong>，这样可以避免这个问题。<br>　　已经知道现有的GeoHash算法使用的是Peano空间填充曲线，这种曲线会产生突变，造成了编码虽然相似但距离可能相差很大的问题，因此在查询附近餐馆时候，首先筛选GeoHash编码相似的POI点，然后进行实际距离计算。</p>
<h2 id="u53C2_u8003_u8FDE_u63A5"><a href="#u53C2_u8003_u8FDE_u63A5" class="headerlink" title="参考连接"></a>参考连接</h2><p><a href="https://en.wikipedia.org/wiki/Geohash" target="_blank" rel="external">https://en.wikipedia.org/wiki/Geohash</a><br><a href="http://blog.jobbole.com/80633/" target="_blank" rel="external">http://blog.jobbole.com/80633/</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/13/gis/1.geohash/" data-id="cijzzpvfx00ff1cfs2f2enofw" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/geohash/">geohash</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-杂项/2.消息推送技术方案" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/12/杂项/2.消息推送技术方案/" class="article-date">
  <time datetime="2016-01-12T14:55:00.000Z" itemprop="datePublished">2016-01-12</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/杂项/">杂项</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/12/杂项/2.消息推送技术方案/">消息推送技术方案</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7279_u70B9"><a href="#u7279_u70B9" class="headerlink" title="特点"></a>特点</h2><p>　　互联网推送消息的方式很常见，特别是移动互联网上，手机每天都能收到好多推送消息，经过研究发现，这些推送服务的原理都是维护一个长连接、，但普通的socket连接对服务器的消耗太大了，所以才会出现像MQTT这种轻量级低消耗的协议来维护长连接。<br>　　首先维护任何一个长连接都需要心跳机制，客户端发送一个心跳给服务器，服务器给客户端一个心跳应答，这样就形成客户端服务器的一次完整的握手，这个握手是让双方都知道他们之间的连接是没有断开，客户端是在线的。如果超过一个时间的阈值，客户端没有收到服务器的应答，或者服务器没有收到客户端的心跳，那么对客户端来说则断开与服务器的连接重新建立一个连接，对服务器来说只要断开这个连接即可。<br>　　在智能手机上的长连接心跳和在Internet上的长连接心跳有什么不同的目的呢？原因就在于智能手机使用的是移动无线网络，那么我们在讲长连接之前我们首先要了解无线移动网络的特点。</p>
<h2 id="u65E0_u7EBF_u79FB_u52A8_u7F51_u7EDC_u7684_u7279_u70B9_uFF1A"><a href="#u65E0_u7EBF_u79FB_u52A8_u7F51_u7EDC_u7684_u7279_u70B9_uFF1A" class="headerlink" title="无线移动网络的特点："></a>无线移动网络的特点：</h2><p>　　当一台智能手机连上移动网络时，其实并没有真正连接上Internet，运营商分配给手机的IP其实是运营商的内网IP，手机终端要连接上Internet还必须通过运营商的网关进行IP地址的转换，这个网关简称为NAT(NetWork Address Translation)，简单来说就是手机终端连接Internet 其实就是移动内网IP，端口，外网IP之间相互映射。相当于在手机终端在移动无线网络这堵墙上打个洞与外面的Internet相连。<br>　　GGSN(GateWay GPRS Support Note 网关GPRS支持节点)模块就实现了NAT功能，由于大部分的移动无线网络运营商为了减少网关NAT映射表的负荷，如果<strong>一个链路有一段时间没有通信时就会删除其对应表，造成链路中断</strong>，正是这种刻意缩短空闲连接的释放超时，原本是想节省信道资源的作用，没想到让互联网的应用不得以远高于正常频率发送心跳来维护推送的长连接。这也是为什么会有之前的信令风暴，微信摇收费的传言，因为这类的应用发送心跳的频率是很短的，既造成了信道资源的浪费，也造成了手机电量的快速消耗。</p>
<h2 id="Android_u548CIOS_u7684_u63A8_u9001_u533A_u522B"><a href="#Android_u548CIOS_u7684_u63A8_u9001_u533A_u522B" class="headerlink" title="Android和IOS的推送区别"></a>Android和IOS的推送区别</h2><p>　　IOS长连接是由系统来维护的，也就是说苹果的IOS系统在系统级别维护了一个客户端和苹果服务器的长链接，IOS上的所有应用上的推送都是先将消息推送到苹果的服务器然后将苹果服务器通过这个系统级别的长链接推送到手机终端上，这样的的几个好处为：<br>　　1. 在手机终端始终只要维护一个长连接即可，而且由于这个长链接是系统级别的不会出现被杀死而无法推送的情况。<br>　　2. 省电，不会出现每个应用都各自维护一个自己的长连接。<br>　　3. 安全，只有在苹果注册的开发者才能够进行推送，等等。<br>　　android的长连接是由每个应用各自维护的，但是google也推出了和苹果技术架构相似的推送框架：C2DM云端推送功能。但是由于google的服务器不在中国境内，其他的原因你懂的，所以导致这个推送无法使用。android的开发者不得不自己去维护一个长链接，于是每个应用如果都24小时在线，那么都得各自维护一个长连接，这种电量和流量的消耗是可想而知的。虽然国内也出现了各种推送平台，但是都无法达到只维护一个长连接这种消耗的级别。</p>
<h2 id="u534F_u8BAE"><a href="#u534F_u8BAE" class="headerlink" title="协议"></a>协议</h2><p>　　MQTT+Apollo，现在用mosquito, 不修改源码情况下, mosquito的topic权限管理比较好. apollo订阅#可以读到所有消息</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/12/杂项/2.消息推送技术方案/" data-id="cijzzpv0j000g1cfspq4d0kyq" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mqtt/">mqtt</a></li></ul>

    </footer>
  </div>
  
</article>


  
  
    <nav id="page-nav">
      <a class="extend prev" rel="prev" href="/page/3/">&laquo; Prev</a><a class="page-number" href="/">1</a><a class="page-number" href="/page/2/">2</a><a class="page-number" href="/page/3/">3</a><span class="page-number current">4</span><a class="page-number" href="/page/5/">5</a><a class="page-number" href="/page/6/">6</a><span class="space">&hellip;</span><a class="page-number" href="/page/15/">15</a><a class="extend next" rel="next" href="/page/5/">Next &raquo;</a>
    </nav>
  
</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/cache/">cache</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/database/">database</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/docker/">docker</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gis/">gis</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/git/">git</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/go/">go</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gradle/">gradle</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/groovy/">groovy</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/hadoop/">hadoop</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/java/">java</a><span class="category-list-count">18</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/linux/">linux</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/log/">log</a><span class="category-list-count">11</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mongodb/">mongodb</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mq/">mq</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mybatis/">mybatis</a><span class="category-list-count">9</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/netty/">netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nginx/">nginx</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nio/">nio</a><span class="category-list-count">19</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nodejs/">nodejs</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/redis/">redis</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/spring/">spring</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/tomcat/">tomcat</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/zookeeper/">zookeeper</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/杂项/">杂项</a><span class="category-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/aop/">aop</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/aspectj/">aspectj</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/cache/">cache</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/classloader/">classloader</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/common-loggings/">common-loggings</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/commonjs/">commonjs</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/database/">database</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/dubbo/">dubbo</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastdfs/">fastdfs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gclib/">gclib</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/geohash/">geohash</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gis/">gis</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/">git</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/">go</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gradle/">gradle</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/groovy/">groovy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hadoop/">hadoop</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hessisan/">hessisan</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a><span class="tag-list-count">48</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/javassist/">javassist</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kafka/">kafka</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log/">log</a><span class="tag-list-count">11</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log4j/">log4j</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/logback/">logback</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/map/">map</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/memecached/">memecached</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mina/">mina</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mongodb/">mongodb</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mq/">mq</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mqtt/">mqtt</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mybatis/">mybatis</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/netty/">netty</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nio/">nio</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/">nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/postgresql/">postgresql</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/">protobuf</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/proxy/">proxy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/push/">push</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rabbitmq/">rabbitmq</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/">redis</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rpc/">rpc</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sitemesh/">sitemesh</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sld/">sld</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/slf4j/">slf4j</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/socket/">socket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spatialite-for-android/">spatialite for android</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spi/">spi</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spring/">spring</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/tomcat/">tomcat</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/transaction/">transaction</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/web/">web</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/xSocket/">xSocket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zbus/">zbus</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zookeeper/">zookeeper</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/数据结构/">数据结构</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/aop/" style="font-size: 15.38px;">aop</a> <a href="/tags/aspectj/" style="font-size: 11.54px;">aspectj</a> <a href="/tags/cache/" style="font-size: 11.54px;">cache</a> <a href="/tags/classloader/" style="font-size: 10px;">classloader</a> <a href="/tags/common-loggings/" style="font-size: 10px;">common-loggings</a> <a href="/tags/commonjs/" style="font-size: 12.31px;">commonjs</a> <a href="/tags/database/" style="font-size: 16.92px;">database</a> <a href="/tags/docker/" style="font-size: 13.85px;">docker</a> <a href="/tags/dubbo/" style="font-size: 10px;">dubbo</a> <a href="/tags/fastdfs/" style="font-size: 10px;">fastdfs</a> <a href="/tags/gclib/" style="font-size: 10.77px;">gclib</a> <a href="/tags/geohash/" style="font-size: 10px;">geohash</a> <a href="/tags/gis/" style="font-size: 10px;">gis</a> <a href="/tags/git/" style="font-size: 10.77px;">git</a> <a href="/tags/go/" style="font-size: 10px;">go</a> <a href="/tags/gradle/" style="font-size: 10px;">gradle</a> <a href="/tags/groovy/" style="font-size: 10px;">groovy</a> <a href="/tags/hadoop/" style="font-size: 10px;">hadoop</a> <a href="/tags/hessisan/" style="font-size: 11.54px;">hessisan</a> <a href="/tags/java/" style="font-size: 20px;">java</a> <a href="/tags/javassist/" style="font-size: 10px;">javassist</a> <a href="/tags/kafka/" style="font-size: 11.54px;">kafka</a> <a href="/tags/linux/" style="font-size: 12.31px;">linux</a> <a href="/tags/log/" style="font-size: 17.69px;">log</a> <a href="/tags/log4j/" style="font-size: 12.31px;">log4j</a> <a href="/tags/logback/" style="font-size: 13.08px;">logback</a> <a href="/tags/map/" style="font-size: 10px;">map</a> <a href="/tags/memecached/" style="font-size: 10.77px;">memecached</a> <a href="/tags/mina/" style="font-size: 13.08px;">mina</a> <a href="/tags/mongodb/" style="font-size: 19.23px;">mongodb</a> <a href="/tags/mq/" style="font-size: 13.85px;">mq</a> <a href="/tags/mqtt/" style="font-size: 10.77px;">mqtt</a> <a href="/tags/mybatis/" style="font-size: 16.15px;">mybatis</a> <a href="/tags/netty/" style="font-size: 10px;">netty</a> <a href="/tags/nginx/" style="font-size: 11.54px;">nginx</a> <a href="/tags/nio/" style="font-size: 13.08px;">nio</a> <a href="/tags/nodejs/" style="font-size: 10px;">nodejs</a> <a href="/tags/postgresql/" style="font-size: 10.77px;">postgresql</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/proxy/" style="font-size: 10px;">proxy</a> <a href="/tags/push/" style="font-size: 10px;">push</a> <a href="/tags/rabbitmq/" style="font-size: 11.54px;">rabbitmq</a> <a href="/tags/redis/" style="font-size: 13.85px;">redis</a> <a href="/tags/rpc/" style="font-size: 19.23px;">rpc</a> <a href="/tags/sitemesh/" style="font-size: 10px;">sitemesh</a> <a href="/tags/sld/" style="font-size: 10px;">sld</a> <a href="/tags/slf4j/" style="font-size: 10px;">slf4j</a> <a href="/tags/socket/" style="font-size: 14.62px;">socket</a> <a href="/tags/spatialite-for-android/" style="font-size: 10px;">spatialite for android</a> <a href="/tags/spi/" style="font-size: 10px;">spi</a> <a href="/tags/spring/" style="font-size: 18.46px;">spring</a> <a href="/tags/tomcat/" style="font-size: 10.77px;">tomcat</a> <a href="/tags/transaction/" style="font-size: 10px;">transaction</a> <a href="/tags/web/" style="font-size: 10px;">web</a> <a href="/tags/xSocket/" style="font-size: 14.62px;">xSocket</a> <a href="/tags/zbus/" style="font-size: 10px;">zbus</a> <a href="/tags/zookeeper/" style="font-size: 10.77px;">zookeeper</a> <a href="/tags/数据结构/" style="font-size: 10.77px;">数据结构</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/01/">January 2016</a><span class="archive-list-count">67</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">December 2015</a><span class="archive-list-count">81</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/11/">November 2015</a><span class="archive-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recents</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/01/30/资料/">(no title)</a>
          </li>
        
          <li>
            <a href="/2016/01/30/java/13.Classloader系列一/">ClassLoader系列一</a>
          </li>
        
          <li>
            <a href="/2016/01/29/hadoop/1.hadoop系列之源码编译/">hadoop系列一之源码编译</a>
          </li>
        
          <li>
            <a href="/2016/01/29/go/1.GO系列之入门/">Go系列一之入门</a>
          </li>
        
          <li>
            <a href="/2016/01/28/tomcat/2.tomcat性能优化/">tomcat性能优化</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2016 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>